package com.javaframe.role.tools;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.ui.ModelMap;

/**
 * Generics��util��.
 *
 */
public class GenericsUtils {
	private static final Log log = LogFactory.getLog(GenericsUtils.class);
	public static final String SQL_ALGORITHM_LIKE = "like";
    public static final String SQL_ALGORITHM_UNLIKE = "unlike";
    public static final String SQL_ALGORITHM_EQUAL = "equal";
    public static final String SQL_ALGORITHM_UNEQUAL = "unequal";
    public static final String SQL_ALGORITHM_LARGE = "large";
    public static final String SQL_ALGORITHM_LARGE_EQUAL = "largeEq";
    public static final String SQL_ALGORITHM_SMALL = "small";
    public static final String SQL_ALGORITHM_SMALL_EQUAL = "smallEq";
    public static final String SQL_ALGORITHM_IN = "in";
    
    public static final Character comma = ',';
	private GenericsUtils() {
	}

	/**
	 * ͨ����,��ö���Classʱ����ĸ���ķ��Ͳ��������. ��public BookManager extends GenricManager<Book>
	 *
	 * @param clazz The class to introspect
	 * @return the first generic declaration, or <code>Object.class</code> if cannot be determined
	 */
	public static Class getSuperClassGenricType(Class clazz) {
		return getSuperClassGenricType(clazz, 0);
	}

	/**
	 * ͨ����,��ö���Classʱ����ĸ���ķ��Ͳ��������. ��public BookManager extends GenricManager<Book>
	 *
	 * @param clazz clazz The class to introspect
	 * @param index the Index of the generic ddeclaration,start from 0.
	 * @return the index generic declaration, or <code>Object.class</code> if cannot be determined
	 */
	public static Class getSuperClassGenricType(Class clazz, int index) {

		Type genType = clazz.getGenericSuperclass();

		if (!(genType instanceof ParameterizedType)) {
			log.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
			return Object.class;
		}

		Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

		if (index >= params.length || index < 0) {
			log.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
					+ params.length);
			return Object.class;
		}
		if (!(params[index] instanceof Class)) {
			log.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
			return Object.class;
		}
		return (Class) params[index];
	}
	/**
	 * 格式化分页管理器<Book>
	 *
	 * @param clazz clazz The class to introspect
	 * @param index the Index of the generic ddeclaration,start from 0.
	 * @return the index generic declaration, or <code>Object.class</code> if cannot be determined
	 */	
	 public static PageInfo formatPageInfo(Map<?, ?> map){
		    PageInfo pageInfo = new PageInfo();
			Map<?,?> page=(Map<?,?>)map.get("pageInfo");
			pageInfo.setNeedDistinct(false);
			pageInfo.setPageSize(Integer.valueOf(page.get("pageSize").toString()));
			if(page.containsKey("pageNo")){
			  pageInfo.setPageNo(Integer.valueOf(page.get("pageNo").toString()));
			}
			return pageInfo;
	 }
	 /**
	 * 格式化过滤管理器<Book>
	 *
	 * @param clazz clazz The class to introspect
	 * @param index the Index of the generic ddeclaration,start from 0.
	 * @return the index generic declaration, or <code>Object.class</code> if cannot be determined
	 */	
	 public static List<ConditionInfo> formatMultiFilter(Map<?, ?> map){
		    List<ConditionInfo> listCondition = new ArrayList<ConditionInfo>();	
			String condition=null;
			String formula=null;
			if(null != map && map.size() > 0){
				//两组过滤器解析
				if(map.containsKey("items")){
				   List<?> items=(List<?>)map.get("items");
				   for(int i=0;i<items.size();i++){
					   Map<?, ?> tempMap=(Map<?, ?>)items.get(i);
					   if(tempMap!=null&&tempMap.containsKey(GenericConstants.CONDITION)){
						   if("fileSize".equals(tempMap.get(GenericConstants.CONDITION).toString())){
							    Long content=((Integer)tempMap.get(GenericConstants.CONTENT)).longValue();
							    listCondition.add(ConditionInfo.newCondition("a."+tempMap.get(GenericConstants.CONDITION), content, ""+tempMap.get(GenericConstants.FORMULA)));
						   }else{
							    if(tempMap.get(GenericConstants.CONTENT) instanceof String){
									String content=tempMap.get(GenericConstants.CONTENT).toString();	
									listCondition.add(ConditionInfo.newCondition("a."+tempMap.get(GenericConstants.CONDITION), content, ""+tempMap.get(GenericConstants.FORMULA)));
								}else if(tempMap.get(GenericConstants.CONTENT) instanceof Integer){
									Integer content=Integer.valueOf(tempMap.get(GenericConstants.CONTENT).toString());	
									listCondition.add(ConditionInfo.newCondition("a."+tempMap.get(GenericConstants.CONDITION), content, ""+tempMap.get(GenericConstants.FORMULA)));
								}else if(tempMap.get(GenericConstants.CONTENT) instanceof Long){
									Long content=Long.valueOf(tempMap.get(GenericConstants.CONTENT).toString());
									listCondition.add(ConditionInfo.newCondition("a."+tempMap.get(GenericConstants.CONDITION), content, ""+tempMap.get(GenericConstants.FORMULA)));
								}else{
									String content=tempMap.get(GenericConstants.CONTENT).toString();
									listCondition.add(ConditionInfo.newCondition("a."+tempMap.get(GenericConstants.CONDITION), content, ""+tempMap.get(GenericConstants.FORMULA)));
								}	
						   }
					   }
				   }
				//子查询过滤器解析   
				}else if(map.containsKey(GenericConstants.CONDITION)){
					if(map.get(GenericConstants.CONTENT) instanceof String){
						String content=map.get(GenericConstants.CONTENT).toString();	
						listCondition.add(ConditionInfo.newCondition("a."+map.get(GenericConstants.CONDITION), content, ""+map.get(GenericConstants.FORMULA)));
					}else if(map.get(GenericConstants.CONTENT) instanceof Integer){
						Integer content=Integer.valueOf(map.get(GenericConstants.CONTENT).toString());	
						listCondition.add(ConditionInfo.newCondition("a."+map.get(GenericConstants.CONDITION), content, ""+map.get(GenericConstants.FORMULA)));
					}else if(map.get(GenericConstants.CONTENT) instanceof Long){
						Long content=Long.valueOf(map.get(GenericConstants.CONTENT).toString());
						listCondition.add(ConditionInfo.newCondition("a."+map.get(GenericConstants.CONDITION), content, ""+map.get(GenericConstants.FORMULA)));
					}	
			    //组合查询过滤器解析 	
				}else 
				   if(map.containsKey("op")){
					 if(map.get("op").equals("all")){
						List<?> datas=(List<?>)map.get("data");				
						for(int i=0;i<datas.size();i++){
							Map<?, ?> data=(Map<?, ?>)datas.get(i);
							formula=conditionMap(data.get("op").toString());
							List<?> subDatas=(List<?>)data.get("data");
							for(int j=0;j<subDatas.size();j++){
								if(((Map<?, ?>)subDatas.get(j)).get("isCol").equals(true)){
									condition=((Map<?, ?>)subDatas.get(j)).get("data").toString();
								}else{
									if(((Map<?, ?>)subDatas.get(j)).get("data") instanceof String){
										String content=((Map<?, ?>)subDatas.get(j)).get("data").toString();	
										listCondition.add(ConditionInfo.newCondition("a."+condition, content, ""+formula));
									}else if(((Map<?, ?>)subDatas.get(j)).get("data") instanceof Integer){
										Integer content=Integer.valueOf(((Map<?, ?>)subDatas.get(j)).get("data").toString());	
										listCondition.add(ConditionInfo.newCondition("a."+condition, content, ""+formula));
									}else if(((Map<?, ?>)subDatas.get(j)).get("data") instanceof Long){
										Long content=Long.valueOf(((Map<?, ?>)subDatas.get(j)).get("data").toString());
										listCondition.add(ConditionInfo.newCondition("a."+condition, content, ""+formula));
									}
								}
							}		
						}
					}else{				
						formula=conditionMap(map.get("op").toString());				
						List<?> datas=(List<?>)map.get("data");
						for(int i=0;i<datas.size();i++){
							if(((Map<?, ?>)datas.get(i)).get("isCol").equals(true)){
								condition=((Map<?, ?>)datas.get(i)).get("data").toString();
							}else{
								if(((Map<?, ?>)datas.get(i)).get("data") instanceof String){
									String content=((Map<?, ?>)datas.get(i)).get("data").toString();	
									listCondition.add(ConditionInfo.newCondition("a."+condition, content, ""+formula));
								}else if(((Map<?, ?>)datas.get(i)).get("data") instanceof Integer){
									Integer content=Integer.valueOf(((Map<?, ?>)datas.get(i)).get("data").toString());	
									listCondition.add(ConditionInfo.newCondition("a."+condition, content, ""+formula));
								}else if(((Map<?, ?>)datas.get(i)).get("data") instanceof Long){
									Long content=Long.valueOf(((Map<?, ?>)datas.get(i)).get("data").toString());
									listCondition.add(ConditionInfo.newCondition("a."+condition, content, ""+formula));
								}	
							}
						}
				   }
				 }
			}
			return listCondition;
	   }
	 public static String conditionMap(String condition){
	       if(condition.equals("contains")){
			   condition="like";
		   }else if(condition.equals("notContains")){
			   condition="unlike";
		   }else if(condition.equals("lessThan")){
			   condition="small";
		   }else if(condition.equals("lessThanOrEqualTo")){
			   condition="smallEq";
		   }else if(condition.equals("largerThan")){
			   condition="large";
		   }else if(condition.equals("largerThanOrEqualTo")){
			   condition="largeEq";
		   }else if(condition.equals("equalTo")){
			   condition="equal";
		   }else if(condition.equals("notEqualTo")){
			   condition="unequal";
		   }
		   return condition;
	   }
	 /**
	 * 格式化响应报文<Book>
	 * @param <T>
	 * @param <T>
	 *
	 * @param clazz clazz The class to introspect
	 * @param index the Index of the generic ddeclaration,start from 0.
	 * @return the index generic declaration, or <code>Object.class</code> if cannot be determined
	 */	
	 public static <T> Map<String, Object> formatResponseData(ModelMap map,List<T> datas,PageInfo page,String identifier){
			map.put("identifier", identifier);
			map.put("items", datas);
			if(!page.equals(null)){
			    map.put("pageInfo", page);
			}
		    return map;	 
	 }
	 /**
		 * 
		 * 【如果value为空，就添加 is null 条件，如果不为空，就添加 = 条件】
		 * 
		 * @author jiangdawei 2010-7-3
		 * @param field
		 * @param value
		 * @param paramList
		 * @return
		 */
		public static String formatNullCondition(String field, Object value, List paramList)
		{
		      String result = "";
		      if(null != value && !"".equals(value))
		      {
		    	  //因为如果value为空，走buildWildCardEqual方法，将不添加任何条件
		    	  result = buildWildCardEqual(field, value, paramList);
		      }
		      else
		      {
		         result = " and " + field + " is null ";
		      }
		      
		      return result;
		   }
		
	   /**
	    * build sql Like
	    * @param paramName, 所查字段
	    * @param paramValueStr, 字段值
	    * @param isMultipleName,  paramValueStr是否包含多个条件值（以逗号分隔）
	    * @return
	    */
	   public static String buildWildCardLike(String paramName, String paramValueStr) {
	      StringBuilder sb = new StringBuilder();
	      if (!GenericsUtils.isEmpty(paramValueStr) && !GenericsUtils.isEmpty(paramName)) {
	         sb.append(" and (");
	         sb.append(GenericsUtils.upperCase(paramName));
	         sb.append(" like ");
	         sb.append(GenericsUtils.upperCase("'%" + GenericsUtils.buildLikeString(paramValueStr) + "%' "));
	        // sb.append(" escape '\\' ");        
	         sb.append(" )");
	      }
	      return sb.toString();
	   }

	   
	   public static String buildWildTimeBetween(String paramName, String paramValueStr) {
		      StringBuilder sb = new StringBuilder();
		      if (!GenericsUtils.isEmpty(paramValueStr) && !GenericsUtils.isEmpty(paramName)) {
		    	  String newStr = paramValueStr.replaceAll("[{}]", "");
	     		 String flag = newStr.split(",")[0].split("=")[1];
	     		 String startTime = newStr.split(",")[1].split("=")[1];
	     		 String endTime = newStr.split(",")[2].split("=")[1];
	     		 
	     		 if(null!=endTime&&endTime.equals("1970-01-01 08:00:00")){
	     			 sb.append(" and (");
			         sb.append(GenericsUtils.upperCase(paramName));
			         sb.append(" > ");
			         //sb.append(" to_timestamp('"+startTime+"','yyyy-MM-dd hh24:mi:ss:ff') ");       
			         sb.append("'"+startTime+"'");
			         sb.append(" )");
	     		 }else if(startTime.equals(endTime)){
	     			 sb.append(" and (");
			         sb.append(GenericsUtils.upperCase(paramName));
			         sb.append(" between ");
			         //sb.append(" to_timestamp('"+startTime+"','yyyy-MM-dd hh24:mi:ss:ff') ");
			         sb.append("'"+startTime+"'");
			         sb.append(" and ");
			         //sb.append(" to_timestamp('"+endTime.split(" ")[0]+" 23:59:59.999999999"+"','yyyy-MM-dd hh24:mi:ss:ff') ");
			         sb.append("'"+endTime.split(" ")[0]+" 23:59:59.999999999"+"'");
			         sb.append(" )");	 
	     		 }else{
			         sb.append(" and (");
			         sb.append(GenericsUtils.upperCase(paramName));
			         sb.append(" between ");
			        // sb.append(" to_timestamp('"+startTime+"','yyyy-MM-dd hh24:mi:ss:ff') ");
			         sb.append("'"+startTime+"'");
			         sb.append(" and ");
			        // sb.append(" to_timestamp('"+endTime+"','yyyy-MM-dd hh24:mi:ss:ff') ");
			         sb.append("'"+endTime+"'");
			         sb.append(" )");
	     		 }
		      }
		      return sb.toString();
		   }
	   /**
	    * build sql Like
	    * @param paramName, 所查字段
	    * @param paramValueStr, 字段值
	    * @param isMultipleName,  paramValueStr是否包含多个条件值（以逗号分隔）
	    * @return
	    */
	   public static String buildWildCardNotLike(String paramName, String paramValueStr) {
	      StringBuilder sb = new StringBuilder();
	      if (!GenericsUtils.isEmpty(paramValueStr) && !GenericsUtils.isEmpty(paramName)) {
	         sb.append(" and (");
	         sb.append(GenericsUtils.upperCase(paramName));
	         sb.append(" not like ");
	         sb.append(GenericsUtils.upperCase("'%" + GenericsUtils.buildLikeString(paramValueStr) + "%' "));
	         //sb.append(" escape '\\' ");
	         sb.append(" )");
	      }
	      return sb.toString();
	   }
	   /**
	    * 
	    * build sql equal
	    * 
	    * @author fufeng 2010-6-28
	    * @param paramName
	    * @param id
	    * @param paramList
	    * @param isIncludeNegative 是否去掉负数-1
	    * @return
	    */
	   public static String buildWildCardEqual(String paramName, Integer id, List paramList, boolean isThrowNegative) {
	      if (isThrowNegative && id == -1) {
	         return "";
	      }
	      return buildWildCardEqual(paramName, id, paramList);
	   }
	   public static String buildWildCardEqual(String paramName, Object paramValue, List paramList) {
	      return buildWildCardWithAlgorithm(paramName, paramValue, paramList, SQL_ALGORITHM_EQUAL);
	   }
	   
	   public static String buildWildCardLarge(String paramName, Object paramValue, List paramList) {
		   return buildWildCardWithAlgorithm(paramName, paramValue, paramList, SQL_ALGORITHM_LARGE);
	   }
	   /**
	    * 
	    * build sql equal
	    * 
	    * @author fufeng 2010-6-28
	    * @param paramName
	    * @param id
	    * @param paramList
	    * @param isIncludeNegative 是否去掉负数-1
	    * @return
	    */
	   public static String buildWildCardUnequal(String paramName, Integer id, List paramList, boolean isThrowNegative) {
	      if (isThrowNegative && id == -1) {
	         return "";
	      }
	      return buildWildCardUnequal(paramName, id, paramList);
	   }
	   public static String buildWildCardUnequal(String paramName, Object paramValue, List paramList) {
	      return buildWildCardWithAlgorithm(paramName, paramValue, paramList, SQL_ALGORITHM_UNEQUAL);
	   }
	   /**
	    * 
	    * 不包括模糊匹配
	    * 
	    * @author fufeng 2010-6-28
	    * @param paramName
	    * @param paramValue
	    * @param paramList
	    * @param algorithm
	    * @return
	    */
	   private static String buildWildCardWithAlgorithm(String paramName, Object paramValue, List<Object> paramList, String algorithm) {
	      StringBuilder sb = new StringBuilder();
	      if (!GenericsUtils.isEmpty(GenericsUtils.toString(paramValue, null)) && !GenericsUtils.isEmpty(paramName)) {
	         sb.append("and ").append(paramName);
	         if (SQL_ALGORITHM_EQUAL.equals(algorithm)) {
	            sb.append(" = ");
	         } else if (SQL_ALGORITHM_UNEQUAL.equals(algorithm)) {
	            sb.append(" <> ");
	         } else if (SQL_ALGORITHM_LARGE.equals(algorithm)) {
	            sb.append(" > ");
	         } else if (SQL_ALGORITHM_LARGE_EQUAL.equals(algorithm)) {
	            sb.append(" >= ");
	         } else if (SQL_ALGORITHM_SMALL.equals(algorithm)) {
	            sb.append(" < ");
	         } else if (SQL_ALGORITHM_SMALL_EQUAL.equals(algorithm)) {
	            sb.append(" <= ");
	         }
	         sb.append(" ? ");
	         paramList.add(paramValue);
	      }
	      return sb.toString();
	   }
	   /**
	    * 
	    * 不包括模糊匹配
	    * 
	    * @author fufeng 2010-6-28
	    * @param paramName
	    * @param paramValue
	    * @param paramList
	    * @param algorithm
	    * @return
	    */
	   public static String buildWildCardIn(String paramName, Object[] paramValue, List paramList) {
	      StringBuilder sb = new StringBuilder(" ");
	      sb.append("and ").append(paramName).append(" in (");
	      for (int i = 0; i < paramValue.length; i++) {
	         sb.append(i == 0 ? "" : ", ").append("?");
	         paramList.add(paramValue[i]);
	      }
	      sb.append(")");
	      return sb.toString();
	   }
	   /**
	    * 
	    * build sql
	    * 
	    * @author fufeng 2010-6-28
	    * @param paramName
	    * @param paramValueStr
	    * @param paramList
	    * @return
	    */
	   public static String buildHqlCondition(String paramName, Object paramValue, List paramList) {
	      return buildHqlCondition(paramName, paramValue, SQL_ALGORITHM_EQUAL, paramList);
	   }
	   public static String buildHqlCondition(String paramName, Object paramValue, String algorithm, List paramList) {
	      StringBuilder sb = new StringBuilder(" ");
	      String paramValueStr = GenericsUtils.toString(paramValue, null);
	      Integer[] conditionIds = getSearchConditionIds(paramValueStr);
	      if (conditionIds != null) {
	         sb.append(buildWildCardIn(paramName, conditionIds, paramList));
	      } else if (!GenericsUtils.isEmpty(paramValueStr) && !GenericsUtils.isEmpty(paramName)) {
	    	 
	    	  
	         if (SQL_ALGORITHM_EQUAL.equals(algorithm)) {
	            sb.append(buildWildCardEqual(paramName, paramValue, paramList));
	         } else if (SQL_ALGORITHM_UNEQUAL.equals(algorithm)) {
	            sb.append(buildWildCardUnequal(paramName, paramValue, paramList));
	         } else if (SQL_ALGORITHM_LARGE.equals(algorithm)) {
	            sb.append(buildWildCardWithAlgorithm(paramName, paramValue, paramList, SQL_ALGORITHM_LARGE));
	         } else if (SQL_ALGORITHM_LARGE_EQUAL.equals(algorithm)) {
	            sb.append(buildWildCardWithAlgorithm(paramName, paramValue, paramList, SQL_ALGORITHM_LARGE_EQUAL));
	         } else if (SQL_ALGORITHM_SMALL.equals(algorithm)) {
	            sb.append(buildWildCardWithAlgorithm(paramName, paramValue, paramList, SQL_ALGORITHM_SMALL));
	         } else if (SQL_ALGORITHM_SMALL_EQUAL.equals(algorithm)) {
	            sb.append(buildWildCardWithAlgorithm(paramName, paramValue, paramList, SQL_ALGORITHM_SMALL_EQUAL));
	         } else if (SQL_ALGORITHM_IN.equals(algorithm)) {
	            Object[] objs = paramValue instanceof Object[] ? (Object[])paramValue : paramValue instanceof List ? ((List)paramValue).toArray() : new Object[]{paramValue};
	            sb.append(buildWildCardIn(paramName, objs, paramList));
	         } else if (SQL_ALGORITHM_LIKE.equals(algorithm)) {
	        	 if(paramValueStr.startsWith("{")&&paramValueStr.endsWith("}")){
	        		 sb.append(buildWildTimeBetween(paramName, paramValueStr));
	        	 }else{
	        		 sb.append(buildWildCardLike(paramName, paramValueStr));
	        	 }
	         } else if (SQL_ALGORITHM_UNLIKE.equals(algorithm)) {
	            sb.append(buildWildCardNotLike(paramName, paramValueStr));
	         }
	   	   		/*}
	      else if(Util.isEmpty(paramValueStr)){
		      if(("equal".equals(algorithm) || "like".equals(algorithm))
		  			 && (null == paramValue || "".equals(paramValue))){
		 		  sb.append(" and "+paramName+" is NULL ");
			   		
		      }*/
	      }
	      return sb.toString();
	   }
	   /**
	    * 
	    * 【对下拉查询条件的string转换成Integer数组】
	    * 
	    * @author fufeng 2010-6-29
	    * @param searchCondition
	    * @return
	    */
	   private static Integer[] getSearchConditionIds(String searchCondition) {
	      String value = searchCondition == null ? "" : searchCondition.trim();
	      if ("".equals(value) || "-1".equals(value)) {
	          return null;
	      }
	      if (value.indexOf(GenericConstants.FLAG_BEGIN) == -1 || value.indexOf(GenericConstants.FLAG_END) == -1) {
	         return null;
	      }
	      value = value.replace(GenericConstants.FLAG_END, "");
	      value = value.replace("-1" + GenericConstants.FLAG_BEGIN, "");
	      value = valueUnFix(value);// 如果值为-1时，要先在查询条件中进行加密
	      String[] temp = value.split(GenericConstants.FLAG_BEGIN);
	      Integer[] integer = new Integer[temp.length];
	      for (int i = 0; i < temp.length; i++) {
	         integer[i] = GenericsUtils.strToInt(temp[i], 0);
	      }
	      return integer;
	   }
	   private static String valueUnFix(String str) {
	      str = str.replace("B-1A", "");
	      return str;
	   }
	   
	   
	   
	   
	   /**
	    * use for Oracle
	    * upper().
	    * 
	    * @param paramValue
	    * @return
	    */
	   public static String upperCase(String paramValue) {
	      if (paramValue == null) {
	         throw new IllegalArgumentException("Null parameter found.");
	      }
	      String ret = "";
	      ret = " upper(" + paramValue + ") ";
	      return ret;
	   }
	   
	   /**
	    * 特殊字符处理
	    * @param sqlStr
	    * @return
	    */
	   public static String buildLikeString(String sqlStr) {
	      if (sqlStr == null) {
	         return "";
	      }
	      sqlStr = sqlStr.trim();
	      sqlStr = sqlStr.replaceAll("\\\\", "\\\\\\\\");
	      sqlStr = sqlStr.replaceAll("_", "\\\\_");
	      sqlStr = sqlStr.replaceAll("'", "''");
	      return sqlStr;
	   }
	 /**
		 *判断字符串是否为空
		 * 
		 * @param s
		 * @return true 表示为空 false 表示不为空
		 */
	   public static boolean isEmpty(String srcStr) {
	      return nvl(srcStr, "").trim().length() == 0 || nvl(srcStr, "").equals("null");
	   }
	   /**
	    * If source String is null, then return object String,else not change;
	    * 
	    * @param srcStr -
	    *           source String
	    * @param objStr -
	    *           object String
	    */
	   public static String nvl(String srcStr, String objStr) {
	      if (srcStr == null || 0 == srcStr.trim().length() || "null".equalsIgnoreCase(srcStr.trim())) {
	         return objStr;
	      } else {
	         return srcStr;
	      }
	   }
		/**
		 *将字符串转换为int
		 * 
		 * @param s
		 * @return int
		 */
		public static int strToInt(String s) {
			int i = -1;
			if (isEmpty(s)) {
				return -1;
			} else {
				try {
					String str = s.replaceAll("[^0-9-]", "");
					i = Integer.valueOf(str);
				} catch (NumberFormatException e) {
					log.error(e.getMessage(), e);
				}
			}
			return i;
		}
		
		/**
		 *将字符串转换为int
		 * 
		 * @param s
		 * @return int
		 */
		public static int strToInt(String s, int defaultInt) {
			int i = defaultInt;
			if (isEmpty(s)) {
				return defaultInt;
			} else {
				try {
					String str = s.replaceAll("[^0-9-]", "");
					i = Integer.valueOf(str);
				} catch (NumberFormatException e) {
					log.error(e.getMessage(), e);
				}
			}
			return i;
		}
		
		public static long strTolong(String s) {
			long l = 0L;
			if (isEmpty(s)) {
				return -1;
			} else {
				try {
					String str = s.replaceAll("[^0-9-]", "");
					l = Long.valueOf(str);
				} catch (NumberFormatException e) {
					log.error(e.getMessage(), e);
				}
			}

			return l;
		}

		/**
		 *将list转换为string
		 * 
		 * @param list
		 * @return string
		 */
		public static int[] listToArr(List<Integer> list) {
			if (list == null || list.size() == 0) {
				return null;
			}

			int len = list.size();
			int[] result = new int[len];
			for (int i = 0; i < len; i++) {
				Integer integer = list.get(i);
				if (integer == null) {
					continue;
				}
				result[i] = integer;
			}
			return result;
		}

		/**
		 *将set转换为string
		 * 
		 * @param set
		 * @return string
		 */
		public static int[] setToArr(Set<Integer> set) {
			if (set == null || set.size() == 0) {
				return null;
			}

			int len = set.size();
			int[] result = new int[len];

			Iterator<Integer> iter = set.iterator();
			int i = 0;

			while (iter.hasNext()) {
				Integer integer = iter.next();
				if (integer == null) {
					continue;
				}
				result[i] = integer;
				i++;
			}
			return result;
		}

		@SuppressWarnings("unchecked")
		public static boolean isEmpty(List list) {
			boolean result = true;
			if (list == null || list.size() == 0 || list.isEmpty()) {
				result = true;
			} else {
				result = false;
			}
			return result;
		}
		
		public static String trimEnd(String str,String regex)
		{
			String result = "";
			if(null != str && !"".equals(str))
			{
				result = str.substring(0,str.length()-regex.length());
			}		
			
			return result;
		}

	   /**
	    * 将字符串转换成HTML语言
	    * 
	    * @param s
	    *           DOCUMENT ME!
	    * @return DOCUMENT ME!
	    */
	   public static String toHTMLString(String s) {
	      if (s == null || "".equals(s)) {
	         return "";
	      }

	      String rtnStr = null;
	      rtnStr = s.replaceAll("\"", "&quot;");
	      rtnStr = rtnStr.replaceAll("<", "&lt;");
	      rtnStr = rtnStr.replaceAll(">", "&gt;");
	      rtnStr = rtnStr.replaceAll("\r\n", "<br/>");
	      rtnStr = rtnStr.replaceAll("\r", "<br/>");
	      rtnStr = rtnStr.replaceAll("\n", "<br/>");
	      rtnStr = rtnStr.replaceAll("'", "&acute;");
	      return rtnStr;
	   }
	   /**
	    * 
	    * 将字符串转换成HTML语言，包括空格
	    * 
	    * @author fufeng 2010-6-28
	    * @param s
	    * @return
	    */
	   public static String toHTMLStringWithSpace(String s) {
	      String rtnStr = toHTMLString(s);
	      return rtnStr.replaceAll(" ", "&nbsp;");

	   }

	   /**
	    * 
	    * 将HTML语言去掉
	    * 
	    * @author fufeng 2010-6-28
	    * @param str
	    * @return
	    */
	   public static String htmlToPlainString(String str) {
	      if (str == null) {
	         return "";
	      }
	      String retValue = str;
	      retValue = retValue.replaceAll("<br/>", "\n");
	      retValue = retValue.replaceAll("&nbsp;", " ");
	      retValue = retValue.replaceAll("&nbsp", " ");
	      retValue = retValue.replaceAll("&acute;", "`");
	      retValue = retValue.replaceAll("&apos;", "\'");
	      retValue = retValue.replaceAll("&quot;", "\"");
	      retValue = retValue.replaceAll("&gt;", ">");
	      retValue = retValue.replaceAll("&lt;", "<");
	      retValue = retValue.replaceAll("&amp;", "&");
	      return retValue;
	   }
	   /**
	    * 
	    * toString
	    * 
	    * @author fufeng 2010-6-28
	    * @param obj
	    * @param defaultStr
	    * @return
	    */
	   public static String toString(Object obj, String defaultStr) {
	      if (null == obj) {
	         return defaultStr;
	      } else {
	         return obj.toString();
	      }
	   }
	   public static Integer toInteger(Object srcStr, Integer defaultValue) {
	      try {
	         if (srcStr != null && isInt(srcStr)) {
	            String s = srcStr.toString().replaceAll("(\\s)", "");
	            return s.length() > 0 ? Integer.valueOf(s) : defaultValue;
	         }
	      } catch (Exception e) {
	         ;
	      }
	      return defaultValue;
	   }
	   public static boolean isInt(Object srcStr) {
	      if (srcStr == null) {
	         return false;
	      }
	      String s = srcStr.toString().replaceAll("(\\s)", "");
	      Pattern p = Pattern.compile("([-]?[\\d]+)");
	      Matcher m = p.matcher(s);
	      return m.matches();
	   }
	   public static String[] splitStringWithEnZhComma(String srcStr) {
	      if (isEmpty(srcStr)) {
	         return null;
	      } else {
	          return srcStr.split("[,\uff0c]");
	      }
	   }
	   
	   /**
	    * 
	    * 判断obj是否在objs中
	    * 
	    * @author fufeng 2010-6-28
	    * @param obj
	    * @param objs
	    * @return
	    */
	   public static boolean isIn(Object obj, Object[] objs) {
	      if (obj == null || objs == null) {
	         return false;
	      }
	      for (Object o : objs) {
	         if (o != null && o.equals(obj)) {
	            return true;
	         }
	      }
	      return false;
	   }
	   /**
	    *将int数组转换为string
	    * 
	    * @param arr
	    * @return string
	    */
	   public static String intArrToStr(int[] arr) {
	      if (arr == null || arr.length == 0) {
	         return null;
	      }

	      StringBuilder sb = new StringBuilder();
	      for (int tmp : arr) {
	         sb.append(tmp);
	         sb.append(",");
	      }

	      int len = sb.length();
	      if (len > 1) {
	         char lastword = sb.charAt(len - 1);
	         if (comma.equals(lastword)) {
	            sb.deleteCharAt(len - 1);
	         }
	      }

	      return sb.toString();
	   }
	   /**
	    * 
	    * 将List转换成sql的in语句，这里是字符串的拼凑
	    * 
	    * @author fufeng 2010-6-28
	    * @param col
	    * @return
	    */
	   public static String toSqlInString(List col) {
	      if (col == null) {
	         return null;
	      }
	      return toSqlInString(col.toArray());
	   }
	   /**
	    * 
	    * 将数组转换成sql的in语句，这里是字符串的拼凑
	    * 
	    * @author fufeng 2010-6-28
	    * @param col
	    * @return
	    */
	   public static String toSqlInString(Object[] col) {
	      if (null == col) {
	         return null;
	      }
	      int index = 0;
	      StringBuilder buf = new StringBuilder();
	      Object value = null;
	      while (index < col.length) {
	         value = col[index];
	         if (value == null) {
	            continue;
	         }
	         if (index != 0) {
	            buf.append(",");
	         }
	         buf.append(addQuote(String.valueOf(value)));
	         index++;
	      }
	      return buf.toString();
	   }
	   /**
	    * 
	    * 为Sql参值加上单引号
	    * 
	    * @author fufeng 2010-6-28
	    * @param value
	    * @return
	    */
	   public static String addQuote(String value) {
	      StringBuilder str = new StringBuilder();
	      if (null == value) {
	         return null;
	      }
	      str.append("\'").append(value).append("\'");
	      return str.toString();
	   } 
}

